import { createEffect, createSignal } from 'solid-js'
import { classNames } from '@violentmonkey/ui'
import styles from './style.module.css'
import { formatSeconds } from '../util'

const EL_SELECTOR = '.s_sectionwrap>[itemtype]'

interface Status {
  done?: boolean
  current?: boolean
  name?: string
  id?: string
  type?: string
}

interface Current {
  name?: string
  duration?: number
  durationText?: string
  timer?: number
  timerText?: string
  status?: string
  id?: string
}

export function App () {
  const [elMap, setElMap] = createSignal<Status[]>([])
  const [current, setCurrent] = createSignal<Current>({})

  const update = () => {
    const list: Status[] = []
    $(EL_SELECTOR).each((i, el) => {
      const id = el.id
      const done = $('.done_icon_show', el).length > 0
      const current = $(el).hasClass('s_pointerct')
      const name = $('.s_pointti', el).text()
      const type = $(el).attr('itemtype')
      list.push({ name, done, current, id, type })
    })
    setElMap(list)
  }

  const play = () => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    $('#mainFrame')[0]?.contentWindow.postMessage('play')
  }

  const playItem = (item: Status) => {
    $(`#${item.id}`).trigger('click')
  }

  const next = () => {
    const listWillPlay: Status[] = elMap()
      .filter(t => !t.done && t.id !== current().id)
    const nextId = listWillPlay[0].id
    if (nextId) {
      $(`#${nextId}`).trigger('click')
    }

    setTimeout(update, 1000)
  }

  createEffect(() => {
    window.addEventListener('message', (event: MessageEvent) => {

      if(event.data === 'play') {
        play()
        return
      }

      if (!elMap()?.length) {
        update()
      }

      const el = $(`${EL_SELECTOR}.s_pointerct`)
      const name = el.text()
      const id = el.attr('id')

      setCurrent({
        ...current(),
        ...event.data,
        name,
        id,
        timerText: formatSeconds(event.data?.timer),
        durationText: formatSeconds(event.data?.duration),
      })

      if (event.data.status === 'ended') {
        setTimeout(next, 10)
      }
    })

    const observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        const $modalBtn = $('.layui-layer-dialog .layui-layer-btn0')
        console.log({ $modalBtn })
        // 处理DOM变化
        console.log(mutation)
      })
    })

    observer.observe(document.body, { childList: true, subtree: true })
    setInterval(update, 5000)
  }, [])

  return (
    <div class={styles.card}>
      <div class={styles.header}>
        <div class={styles.title}>
          自动播放脚本
        </div>
        <div class={styles.ext}>
          <a onClick={update} class={styles.btn}>分析</a>
          <a onClick={play} class={styles.btn}>播放</a>
        </div>
      </div>
      <div class={styles.body}>
        {!elMap()?.length && '请分析数据！'}

        {current().name && <div class={styles.currentCard}>
          <div>当前播放：{current().name}</div>
          <div style={{display:'inline-flex', 'justify-content': 'space-between'}}>
            <div style={{'margin-right':'10px'}}>进度：{((current().timer / current().duration) * 100).toFixed(
              2)} %
            </div>
            <div style={{'margin-right':'10px'}}>状态：{current().status}</div>
            <div style={{'margin-right':'10px'}}>当前：{current().timerText}/{current().durationText}</div>
          </div>
        </div>}

        <div style={{ 'max-height': '400px', overflow: 'auto' }}>
          {elMap()?.map(item => <div
            class={classNames([
              styles.learnItem,
              item.done ? styles.learnItemDone : '',
              item.current ? styles.learnItemCurrent : '',
            ])}
          >
            <div class={styles.learnItemTitle}>
              <a class={styles.play}
                 onClick={() => playItem(item)}>播放</a> &nbsp; {item.name}
            </div>
            <div class={styles.learnItemExt}>
              {item.current && <div class={styles.learnItemExtItem}>🚩</div>}
              {item.done && <div class={styles.learnItemExtItem}>✔</div>}
            </div>
          </div>)}
        </div>
      </div>

    </div>
  )
}
